<script>
import axios from "axios";

export default {
  name: "updateAddr",
  props: ["updateForm"],
  data() {
    var checkMobile = (rule, value, callback) => {
      const regUser = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      if (regUser.test(value)) {
        return callback()
      }else {
        if (value.length !== 11) {
          callback(new Error('手机号码长度应该是11位'))
        }
        callback(new Error("手机号格式不正确"))
      }
    }
    return {
      updateFormVisible: true,
      rules: {
        name: [
          {required: true, message: '请输入收货人', trigger: 'blur'},
          {min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, validator: checkMobile, trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ]
      }
    }
  }, methods: {
    submitUpdateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$api.address.updateAddressById(this.updateForm).then((res) => {
            var data = res.data;
            if (data.success) {
              this.$message.success("修改成功")
              this.$refs[formName].resetFields();
              this.updateFormVisible = false
            } else {
              this.$message.error(data.message);
            }
          }).catch((resp) => {
            this.$message.error('服务器访问失败' + resp);
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cancelUpdateSubmit(formName) {
      this.$refs[formName].resetFields();
      this.updateFormVisible = false
    },
  }, watch: {
    updateFormVisible() {
      this.$emit('changeVal', this.updateFormVisible)
    }
  }
}
</script>

<template>
  <el-dialog title="修改地址" :visible.sync="updateFormVisible" :append-to-body="true">
    <el-form :model="updateForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="收货人" prop="name">
        <el-input v-model="updateForm.name"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model.number="updateForm.phone" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-input v-model="updateForm.address"></el-input>
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="updateForm.tag"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpdateForm('ruleForm')">确定</el-button>
        <el-button @click="cancelUpdateSubmit('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>

</style>